route.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { OpenaiPath } from "@/app/constant";
  2. import { prettyObject } from "@/app/utils/format";
  3. import { NextRequest, NextResponse } from "next/server";
  4. import { auth } from "../../auth";
  5. import { requestOpenai } from "../../common";
  6. const ALLOWD_PATH = new Set(Object.values(OpenaiPath));
  7. async function handle(
  8. req: NextRequest,
  9. { params }: { params: { path: string[] } },
  10. ) {
  11. console.log("[OpenAI Route] params ", params);
  12. if (req.method === "OPTIONS") {
  13. return NextResponse.json({ body: "OK" }, { status: 200 });
  14. }
  15. const subpath = params.path.join("/");
  16. if (!ALLOWD_PATH.has(subpath)) {
  17. console.log("[OpenAI Route] forbidden path ", subpath);
  18. return NextResponse.json(
  19. {
  20. error: true,
  21. msg: "you are not allowed to request " + subpath,
  22. },
  23. {
  24. status: 403,
  25. },
  26. );
  27. }
  28. const authResult = auth(req);
  29. if (authResult.error) {
  30. return NextResponse.json(authResult, {
  31. status: 401,
  32. });
  33. }
  34. try {
  35. return await requestOpenai(req);
  36. } catch (e) {
  37. console.error("[OpenAI] ", e);
  38. return NextResponse.json(prettyObject(e));
  39. }
  40. }
  41. export const GET = handle;
  42. export const POST = handle;
  43. export const runtime = "edge";